<template>
  <div style=" ">
    <div class="top-box">
      <div class="top-left-title" @click="tomain">AI助学系统</div>
	  <img src="https://openres.xfyun.cn/xfyundoc/2024-02-26/d98eb1cf-f074-4628-a896-6136bffe11af/1708931804132/spk.png" style="margin-right: 5px;position: relative;top: 0px;transform: scale(0.7);
	  "/>
	  
      <div class="top-menu-list">
        <div class="active-no" @click="to01">智慧课堂</div>
        <!-- <div  class="active-no" @click="to02">智慧诊断</div> -->
        <div class="active-no" @click="to03">助学提升</div>
        <div @click="to04" class="active-no">学情监测</div>
        <div @click="to05" style="border-bottom: 3px solid #fff;font-size: 20px">智能翻译</div>
      </div>
      <div class="user-box">
        <i class="el-icon-message" style="color: #fff;position: relative;top: 10px;"></i>
        <div class="user-image"><img style="width: 35px;height: 35px;border-radius: 100px;object-fit: contain" src="https://img1.baidu.com/it/u=1856720522,683752130&fm=253&fmt=auto&app=138&f=JPEG?w=529&h=500" /></div>
      </div>
    </div>
  <!--  电脑界面-->
  <div class="pc-chat-container" v-loading="isWxLogin" element-loading-text="微信登录中请稍等" element-loading-spinner="el-icon-loading">
    <div class="pc-dialog-box" style="width: 100%">
      <div class="logo-warp" v-if="messageList2.length === 0">
        <div class="logo-hasno">
          <img src="https://zk.yaoxuankeji.club:8199/images/435FDC028D96520BA6F9253E06B9598B.png">
        </div>
      </div>
      <!--      电脑对话框-->
      <div class="pc-dialog-box-chat" style="width: 100%">
        <div class="chatgpt-box" ref="scrollContainer" id="chatgpt-box" style="width: 100%" :style="{paddingTop:phonePaddingTop+'px'}">
          <div class="some-an" v-for="item in messageList2" v-bind:key="item.id" >
            <div class="some-anin">
              <div class="content-chat" v-if="item.role==='user'">
                <div style="display: flex;width: 51%" :style="{width:phoneWidth+'%'}">
                  <img src="https://img0.baidu.com/it/u=2791937989,1279599168&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500">
                  <span>{{item.content}}</span>
                </div>
              </div>
              <div class="content-chat-2" v-else-if="item.role==='assistant'" style="border-bottom: 1px solid #d9d9e3;border-top: 1px solid #d9d9e3;">
                <div style="display: flex;width: 51%" :style="{width:phoneWidth+'%'}">
                  <!-- <div class="content-icon"><img src="https://img1.baidu.com/it/u=3613958228,3522035000&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"/></div> -->
                  <div class="content-icon"><img src="https://zk.yaoxuankeji.club:8199/images/435FDC028D96520BA6F9253E06B9598B.png"/></div>
                  <!--<markdown-it-vue :content="item.content" class="markdown" style="background: transparent;display: flex;-->
    <!--align-items: center;">-->
                  <!--</markdown-it-vue>-->
                  <div style="max-width: 70%;white-space: pre-line;">{{item.content}}</div>

                </div>
                <el-rate v-model="item.score" @change="changeScore(item)" style="display: flex;width:51%;margin-top: 5px;justify-content: flex-end;position: relative;right: 15px" :style="{width:phoneWidth+'%'}"></el-rate>

              </div>
            </div>
          </div>
        </div>
      </div>
      <!--      电脑输入框-->
      <div class="pc-import-box" style="width: 100%">
        <!--        电脑输入框-->
        <div @click="reset()" class="reload-button" v-if="messageList2[0]&&!textLoading&&isConnected && (openmenuWidth === 100 || (openmenuWidth === 100 && !leftMenu))">口&nbsp;&nbsp;&nbsp;&nbsp;重新回答</div>
        <div @click="stopAnswer()" class="reload-button" v-if="messageList2[0]&&textLoading&&isConnected">口&nbsp;&nbsp;&nbsp;&nbsp;暂停回答</div>
        <div class="pc-import">
          <input type="text" v-model="messageSend" class="inputStyle" placeholder="请输入内容..." @keydown.enter="messageSendlisten">
          <div class="pc-import-button-box" :style="{cursor:inputText ? 'pointer':'false'}" @click="sendMessage()">
            <i class="el-icon-s-promotion post-button" :style="{color: inputText ? 'rgba(0,0,0,.5)' : '#DDDDE3'}"></i>
          </div>
        </div>
        <!--        产品提示-->
        <div class="product-tips" >
          <!--对话内容仅供参考-->
          <!--<a href="https://beian.miit.gov.cn/"  target="blank" style="font-size: 18px;color: rgba(0,0,0,0.8)">鄂ICP备2022020033号-2</a>-->
        </div>
      </div>
    </div>
    <div class="dialog-box" v-if="loginBox" >
      <div style="z-index: 2000;width: 100%;height: 100%;position: fixed" @click="loginBox = false"></div>
      <div class="login-box" >
        <div class="login-tip">
          <span>用户登录</span>
        </div>
        <el-form ref="loginForm" :model="loginForm" label-width="80px">
          <el-form-item label="手机号码">
            <el-input v-model="loginForm.username"></el-input>
          </el-form-item>
          <el-form-item label="验证码">
            <el-input v-model="loginForm.code" style="width: 55%"></el-input>
            <el-button type="primary" @click="sendCode()" :disabled="codeDisabled" style="position: absolute;right: 0;">{{codeText}}</el-button>
          </el-form-item>
        </el-form>
        <div slot="footer" style="width: 350px;text-align: center">
          <el-button @click="loginBox = false">取 消</el-button>
          <el-button type="primary" @click="userLogin()">确 定</el-button>
        </div>
      </div>
    </div>
    <!-- shop -->
    <el-dialog
      title="升级服务"
      :visible.sync="isShop"
      width="70%">
      <div style="display: flex; flex-direction: column; align-items: center;">
        <div style="font-size: 20px; font-weight: 800;">
          加群了解
        </div>
        <div style="text-align: center; margin-top: 20px;">
          <el-image
            class="group-image"
            :src="adminUrl"
            fit="fill"></el-image>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
            <el-button @click="isShop = false">取 消</el-button>
            <el-button type="primary" @click="isShop = false">确 定</el-button>
        </span>
    </el-dialog>
  </div>
  </div>
</template>

<script>
  const admin = require('@/assets/admin.png')

  // import MarkdownItVue from 'markdown-it-vue'
  // import 'markdown-it-vue/dist/markdown-it-vue.css'
  // import { sendCode } from '@/api/user'
  import { getToken } from '@/utils/auth'
  // import { nanoid } from 'nanoid'
  // import { commitQuestion, scoreChange, getCommitQuestionInfo, getPhone } from '@/api/chat'
  export default {
    name: 'chat',
    components: {
      // MarkdownItVue
    },
    data() {
      return {
        codeText:"发送验证码",//验证码
        codeDisabled:false,// 是否禁止发送验证码
        loginForm: {
          username: '',
          code: ''
        },// 登录表单
        loginBox:false, // 登录矿口
        leftMenu:true,
        inputText:"",
        postUrl:"",
        // new 受点击
        isHovering:false,//new点击情况
        chatList:[{id:1,text:"new chat"},
          {id:2,text:"new chat"},
          {id:3,text:"new chat"}
        ],
        messageList2:[
          // {
          //     role:"user",
          //     content:"你是谁"
          // },
          // {
          //     role:"assistant",
          //     content:"我是gpt"
          // }
        ],
        windowWidth: document.documentElement.clientWidth,  //实时屏幕宽度
        windowHeight: document.documentElement.clientHeight,   //实时屏幕高度
        phoneSWidth:"",
        phoneWidth:"",
        height:0,
        loginBoxWidth:null,// 登录表宽度
        messageSend:"",// 输入框文本
        messageList:[],// 传送给服务器的数据，和messageList2一致，格式不同
        textLoading:false,// 是否禁止输入框输入
        isConnected:false,
        openmenuWidth:null,
        phonePaddingTop:null,// 对话框整体下移,
        isNewChat:false,// 是否开一个新的聊天窗口
        isChatting:null,//对应的正在进行的聊天的窗口id
        isLogin:false,// 登录状态
        isPhone:false,
        userInfo: '', //用户提问状态,
        isChangeUserInfo: true,
        phone: '',
        isWxLogin: false,
        isShop: false,
        adminUrl: admin
      };
    },
    methods:{
      //用户登录的方法
      userLogin(){
        // 用户登录的方法
        if(this.loginForm.username === '' || this.loginForm.code === '') {
          this.$message.error("手机号或验证码未输入")
          return
        }
        const data = {
          username: this.loginForm.username,
          password: this.loginForm.code
        }
        this.$store.dispatch('user/login', data).then(res => {
          console.log(res)
          if(res.code === 200) {
            //登录成功后，修改登录状态
            this.$message.success('登录成功')
            this.isLogin = true
            this.loginBox = false
            this.getUserInfo()
            // 拿到用户的手机号
            this.getPhone()
          }
        })
      },
      // 发送验证码
      sendCode(){
        // console.log("###")
        // 判断手机号是否为空
        if (!this.loginForm.username) {
          this.$message.error('请输入手机号');
        }else{
          const regExp = /^1[3456789]\d{9}$/;
          if (!regExp.test(String(this.loginForm.username))) {
            this.$message.error('手机号格式不正确');
            console.log(this.loginForm.username)
          }else{
            // 发送验证码的逻辑
            // ...
            // console.log("###")
            const data = {
              phoneNumber: this.loginForm.username
            }
            // sendCode(data).then(res => {
            //   console.log(res)
            //   this.$message.success('已发送验证码')
            //   // 发送成功后，设置 codeDisabled 为 true，codeText 为倒计时
            //   this.codeDisabled = true;
            //   let count = 60;
            //   const timer = setInterval(() => {
            //     count--;
            //     if (count === 0) {
            //       clearInterval(timer);
            //       this.codeDisabled = false;
            //       this.codeText = '发送验证码';
            //     } else {
            //       this.codeText = `${count}s 后重新发送`;
            //     }
            //   }, 1000);
            // })
          }
        }
      },
      // 点击聊天列表，加载聊天内容
      loadChatContent(val,e){
        this.isChatting = val.id;
        let leftMenu = document.getElementsByClassName("pc-post");
        console.log(this.isPhone)
        if (this.isPhone){
          this.closeMenu()
        }
        for (let i=0;i<leftMenu.length;i++){
          leftMenu[i].className = "pc-post"
        }
        if (e.target.className === "pc-post"){
          e.target.className = "pc-post pc-post-active"
        }else{
          e.srcElement.parentElement.className = "pc-post pc-post-active"
        }
        console.log(this.isChatting)
        this.messageList2 = val.messageList2
        this.isNewChat = false

      },
      // 开启新的聊天窗口
      openNewChat(){
        this.isNewChat = true
        this.messageList2 = []
        let leftMenu = document.getElementsByClassName("pc-post")
        for (let i=0;i<leftMenu.length;i++){
          leftMenu[i].className = "pc-post"
        }
        if (this.isPhone){
          this.closeMenu()
        }
      },
      // 写入本地缓存的聊天列表
      wrightLocalChatList(){

        localStorage.setItem("chatList",JSON.stringify(this.chatList));
      },
      // 将聊天内容写入聊天列表
      wrightToChatList(messageList){
        for (let i=0;i<this.chatList.length;i++){
          console.log(this.isChatting)
          console.log(this.chatList[i].id)
          if (this.isChatting === this.chatList[i].id){
            this.chatList[i].messageList2 =  messageList
            break
          }
        }
        console.log(this.chatList)
        this.wrightLocalChatList()
      },
      // 读取本地缓存的聊天列表
      loadLocalChatList(){
        this.chatList = JSON.parse(localStorage.getItem("chatList"))
        console.log(this.chatList)
        if (this.chatList === null){
          this.chatList = []
          this.openNewChat()
        }else{
          this.openNewChat()
          console.log(this.isChatting)
          // this.isChatting = this.chatList[0].id
          // console.log(this.isChatting)
        }
      },
      // 开启菜单，手机界面
      openMenu(){
        this.leftMenu = true
        this.openmenuWidth = 0
      },
      // 关闭菜单，手机页面
      closeMenu(){
        this.leftMenu = false
        this.openmenuWidth = 100
      },
      // 暂停回答，停止接受信息，即为关闭websocket，重启
      stopAnswer(){
        this.openSocket()
      },
      // 发送消息至服务端之前进行裁剪
      checkMessage(){
        this.messageList = []
        let newMessageList = this.messageList2.slice(-5)
        for (let i =0;i<newMessageList.length;i++){
          let jsonform = {
            role : newMessageList[i].role,
            content : newMessageList[i].content
          }
          // 注意，发送的列表为 messageList，messageList2为 展现到页面的列表，但两者内容一样，只是格式不同，messList2为JSON格式，messageList为JSON字符串格式。
          this.messageList.push(JSON.stringify(jsonform))
          console.log(jsonform)
        }
      },
      //重新发送
      reset(){
        console.log(this.messageList2)
        console.log(this.messageList)
        // 输入框禁止输入
        this.textLoading=true
        // 如果最后的结尾为对话为user，则发送消息至服务端；若为assistant，则删除最后一条消息，再发送该消息。
        if (this.messageList2[this.messageList2.length-1].role === "user"){
          console.log(this.messageList2)
          this.checkMessage()
          this.contentText = "";
          let message = this.messageList.toString();
          this.socket.send(message)
        }else{
          this.messageList2 = this.messageList2.splice(0,this.messageList2.length-1)
          this.messageList = []
          for (let i =0;i<this.messageList2.length;i++){
            let jsonform = {
              role : this.messageList2[i].role,
              content : this.messageList2[i].content + ",联合国五常语言互译（附带语言类型）"
            }
            this.messageList.push(JSON.stringify(jsonform))
          }
          console.log(this.messageList2)
          console.log(this.messageList)
          let message = this.messageList.toString();
          this.contentText = "";
          this.socket.send(message)
          console.log(this.messageList)
        }
      },
      // 定义将滚动条定位在底部的方法
      scrollToBottom(){
        this.$nextTick(()=>{
          let chat = this.$el.querySelector("#chatgpt-box")
          chat.scrollTop = chat.scrollHeight
        })
      },
      highlighter (code) {
        return highlight(code, languages.js)
      },
      messageSendlisten(event) {
        console.log(event)
        if (event.keyCode === 13) {
          this.sendMessage(); // 发送文本
          event.preventDefault(); // 阻止浏览器默认换行操作
          return false;
        }
      },
      // 生成随机数，websocket的连接用户id。后期将改为用户的唯一主键id
      outNumber(){
        function getRandomNumber() {
          return Math.floor(Math.random() * (9999999999 - 100000000 + 1) + 100000000);
        }
        var randomNumber = getRandomNumber();
        return randomNumber;
      },
      insideData(role,content){
        this.messageList.push(role)
        this.messageList.push(content)
      },
      // 通过websocket发送消息
      sendMessage(){
        let i=1
        //!this.isLogin
        if(i==!1){
          this.$message.error("请先登录")
        }else {
          if(this.messageSend === '') {
            this.$message.error('请输入内容！')
            return
          }
          if(this.isChangeUserInfo === true) {
            // this.$message.info('正在更新用户信息，请重新发送')
            // return
          }
          if(this.userInfo === '') {
            // this.$message.error("提问异常")
            // return
          }
          console.log(+this.userInfo['剩余总提问次数'])
          if((this.userInfo['剩余总提问次数'] === null || (+this.userInfo['剩余总提问次数']) <= 0) && this.userInfo['用户会员等级'] === 0) {
            this.$message.error("请升级服务")
            return
          }
          // 判断是否在发送消息，若在发送消息，则不能发送新的消息
          if (this.textLoading === true) {
            this.$message.error('请稍等，正在生成');
          } else {
            if (this.isNewChat){
              let chatID = this.outNumber()
              let chatJson = {
                "id" : chatID,
                "text" : this.messageSend,
              }
              this.isChatting = chatID
              this.chatList.unshift(chatJson)
              setTimeout(() => {
                document.getElementsByClassName("pc-post")[0].className = "pc-post pc-post-active";
                this.isNewChat = false
              }, 0)

            }
            let that = this
            // let message = {from: "zhuchao", to:"zhuchao", text: "你是谁"}
            this.socket = this.$store.state.socket;
            let chatModel = {
              role: "user",
              content: this.messageSend
            };
            let chatModel2 = {
              role: "user",
              content: this.messageSend + ",联合国五常语言互译（附带语言类型）"
            };
            console.log(chatModel2)
            this.messageList.push(JSON.stringify(chatModel2));
            console.log(this.messageList)
            this.messageList2.push(chatModel);
            // this.checkMessage()
            console.log(this.messageList);
            // this.insideData("user",this.messageSend)
            let message = this.messageList.toString();
            this.contentText = "";
            this.contentText = this.messageSend + "\n";
            console.log(this.socket.readyState,WebSocket.OPEN)
            if (this.socket.readyState === WebSocket.OPEN){
              console.log(message)
              this.socket.send(message)
            }else{
              this.$message.error("暂时无法发送消息，与服务器的连接已断开")
            }
            this.contentText = "";
            this.textLoading = true;
            this.messageSend = ""
          }
          // }else{
          //     this.$message.error('请先激活');
        }
      },
      // 开启 websocket
      openSocket(){
        // 开启websocket传入的随机连接用户id
        let randomID = this.outNumber()
        // let socketUrl = "ws://localhost:8099/chatInWord2/zhuchao";
        let socketUrl = "ws://43.135.182.28:8099/chatInWord2/"+randomID;
        // 全局配置
        this.socket = this.$store.state.socket;
        if (this.socket != null) {
          this.socket.close();
          this.socket = null;
          this.$store.state.socket = null
          console.log('已关闭连接')
          this.isConnected = false
        }
        this.socket = new WebSocket(socketUrl);
        this.$message('建立连接中......');
        let that = this;
        this.socket.onopen = function () {
          console.log("websocket已打开");
          that.isConnected = true
          that.$store.state.socket = that.socket;
          that.getData()
          // that.watchWebsocket()
          // 定期发送心跳消息
          // that.intervalId = setInterval(() => {
          //     console.log(123)
          //     that.socket.send('chatPing')
          // }, 3000)
        };
      },
      watchWebsocket(){
        let that = this;
        this.socket = this.$store.state.socket;
        this.socket.onclose = (res) => {
          console.log("websocket已被关闭");
          console.log(that.socket)
          console.log(that.$store.state.socket)
          // that.$message.error("websocket已被关闭");
          that.isConnected = false
          console.log(res)
          // 停止心跳检测并重新连接WebSocket
          // clearInterval(this.intervalId)
          // that.openSocket()
          that.reloads = true
          console.log(that.reloads,that.isConnected)
        }
        this.socket.onError= () =>{
          console.log("websocke出错已被关闭");
          // this.$message.error("websocket出错已被关闭");
          this.isConnected = false
        }

        // 当websocket被关闭，重新连接后，重新发送消息，暂时取消该功能
        setTimeout(() => {
          if (that.reloads)
            if (that.messageList2[that.messageList2.length-1].content === "错误提问"){
              that.textLoading = false
              this.isConnected = true
            }else{
              // that.reset()
              that.textLoading = false
              console.log("重新发送")
              this.isConnected = true

            }
        }, 1500)
      },
      getData(){
        console.log("建立连接中......");
        this.socket = this.$store.state.socket;
        let that = this;
        this.watchWebsocket();
        this.socket.onmessage = function (msg) {
          // console.log("收到数据====" + msg.data);
          if (msg.data === "" || msg.data === "\n" || msg.data===null){
            // that.contentText += "\n";

            // that.insideData("assistant",that.contentText)
            console.log(that.messageList2)
          }else{
            let data = msg.data;
            // 服务端开始发送消息，会传入一个begin，告诉这是一条新的信息
            if (msg.data === "begin"){
              let reciveMessaage = {
                // id:  nanoid(),
                role : "assistant",
                content: ""
              }
              that.messageList2.push(reciveMessaage)
              that.textLoading = true
              // 服务端结束发送消息，会传入一个end，告诉这条信息的内容结束了
            }else if(msg.data === "end"){
              that.messageList2[that.messageList2.length-1].content += "\n";
              let reciveMessaage = {
                role : "assistant",
                content: that.contentText.replace("\\n\\n","\n\n").replace(/\\n/g,"\n").replace("\\\"",'"').replace("\\\\n","\n").replace("\\\\\\\"",'"').replace("\\\n","\n").replace(/\\t/g,"   ").replace(/\\/g,"\\")
              };
              that.messageList.push(JSON.stringify(reciveMessaage));
              that.wrightToChatList(that.messageList2);
              console.log(that.messageList)
              console.log(that.messageList2)
              that.textLoading = false


              // that.commitQuestion()
              // 若传入的为其他内容，那么就是信息的内容，存入数组
            }else{
              // console.log(msg)
              data = data.substr(1);
              data = data.substr(0,data.length-1);
              // console.log(data);
              that.messageList2[that.messageList2.length-1].content += data.replace(/\\n\\n/g,"\n\n").replace(/\\n/g,"\n").replace("\\\"",'"').replace("\\\\n","\n").replace("\\\\\\\"",'"').replace("\\t","    ").replace(/\\\\\\n/g,"\n").replace(/\\/g,"\\");
              // const md = new MarkdownIt();
              // that.messageList2[that.messageList2.length-1].content =  md.render(that.messageList2[that.messageList2.length-1].content);
              // that.$nextTick(()=>{
              //
              //     const blocks = this.$refs.mdRef.$el.querySelectorAll('pre code')
              //
              //     blocks.forEach((block) => {
              //
              //         Hljs.highlightBlock(block)
              //
              //     })
              //
              // })
              that.contentText += data
              that.textLoading = true
              that.scrollToBottom()
            }
            // console.log(!that.messageList2[1].content)
          }
        }
        console.log("建立连接成功")
        this.$message({
          message: '恭喜你，建立连接成功',
          type: 'success'
        });
        this.isConnected = true
        this.textLoading=false
        console.log(this.socket)
      },
      // 挂载到vue的生命周期上，时刻监听屏幕的宽度和高度的变化，以达到自适应的效果
      watchWidth(){
        var that = this;
        // <!--把window.onresize事件挂在到mounted函数上-->
        window.onresize = () => {
          return (() => {
            window.fullHeight = document.documentElement.clientHeight;
            window.fullWidth = document.documentElement.clientWidth;
            that.windowHeight = window.fullHeight;  // 高
            that.windowWidth = window.fullWidth; // 宽
          })()
        };
      },
      // 文本复制（目前在手机不起效果）
      coopText(){
        // 获取所有的<pre>标签
        const preTags = document.querySelectorAll('pre');
        // 循环遍历<pre>标签
        let that = this
        preTags.forEach(preTag => {
          if (preTag.childNodes.length<2){
            // 创建复制按钮
            const copyButton = document.createElement('i');
            copyButton.className = "el-icon-copy-document copy-content"
            copyButton.hover = "color:red"
            copyButton.type = "button"
            // copyButton.innerText = '复制';
            copyButton.style = "display: block;\n" +
              "position: absolute;\n" +
              "right: 18px;\n" +
              "top: 8px;\n" +
              "width: 25px;\n" +
              "height: 35px;\n" +
              "background: #746f6f;\n" +
              "border-radius: 4px;\n" +
              "display: flex;\n" +
              "    justify-content: center;\n" +
              "    align-items: center;\n" +
              "    "
            copyButton.setAttribute("icon","el-icon-copy-document")
            // 将按钮添加到<pre>标签中
            preTag.appendChild(copyButton);
            // 添加点击事件
            copyButton.addEventListener('click', (res) => {
              copyButton.setAttribute("textData",preTag.innerText)
              // 复制<pre>标签中的文本内容
              let m = document.execCommand('Copy');
              console.log(m)
              if (window.clipboardData) {
                this.$message.success("已复制文本")
                window.clipboardData.setData('text',preTag.innerText);
              }else{
                (function () {
                  document.oncopy = function (e) {
                    e.clipboardData.setData('text',preTag.innerText);
                    e.preventDefault();
                    document.oncopy = null;
                  }
                })(preTag.innerText);
                document.execCommand('Copy');
                this.$message.success("已复制文本")
              }

            });


            // 针对markdown-body的文本复制

          }

        });


        // 针对markdown-body的文本复制
        const preTagsBody = document.querySelectorAll('.content-chat-2');
        // 循环遍历<pre>标签
        preTagsBody.forEach(preTag => {
          if (preTag.lastChild.className !== "el-icon-copy-document copy-contents"){
            // 创建复制按钮
            const copyButton = document.createElement('i');
            copyButton.className = "el-icon-copy-document copy-contents"
            copyButton.hover = "color:red"
            copyButton.type = "button"
            // copyButton.innerText = '复制';
            copyButton.style = "display: block;\n" +
              "position: absolute;\n" +
              "right: 5px;\n" +
              "bottom: 8px;\n" +
              "width: 25px;\n" +
              "height: 35px;\n" +
              "background: rgb(255 255 255);\n" +
              "border-radius: 4px;\n" +
              "display: flex;\n" +
              "    justify-content: center;\n" +
              "    align-items: center;\n" +
              "    "
            copyButton.setAttribute("icon","el-icon-copy-document")
            // 将按钮添加到<pre>标签中
            preTag.appendChild(copyButton);
            // 添加点击事件
            copyButton.addEventListener('click', (res) => {
              copyButton.setAttribute("textData",preTag.innerText)
              // 复制<pre>标签中的文本内容
              let m = document.execCommand('Copy');
              // if (window.clipboardData) {
              //     this.$message.success("已复制文本")
              //     copyButton.select()
              //     window.clipboardData.setData('text',preTag.innerText);
              // }else{
              (function () {
                document.oncopy = function (e) {
                  e.clipboardData.setData('text',preTag.innerText);
                  e.preventDefault();
                  document.oncopy = null;
                }
              })(preTag.innerText);
              document.execCommand('Copy');
              this.$message.success("已复制文本")
              // }
            });
          }
        });
      },
      tomain() {
        this.$router.push("/page5")
      },
      to01() {
        this.$router.push("/")
      },
      to02() {
        this.$router.push("/page2")
      },
      to03() {
        this.$router.push("/page3")
      },
      to04() {
        this.$router.push("/page4")
      },
      to08() {
        this.$router.push("/page8")
      },
      to05(){
        this.$router.push("/chat")
      },
      // 前往购买vip
      toShop() {

        if(this.isLogin === false) {
          this.$message.error('请先登录')
          return
        }
        this.isShop = true

      },
      // 评分
      changeScore(item) {
        console.log(item)
        let data = {
          dialogueId: item.id,
          score: item.score
        }
        console.log(data)
        scoreChange(data).then(res => {
          this.$message.success('评分成功')
        })
      },
      // 提交问答
      commitQuestion() {
        // 发送完这条提问后
        this.userInfo = ''
        this.isChangeUserInfo = true
        console.log(this.messageList2)
        let created = ''
        const date = new Date()
        created = date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate()
        created += ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds()
        const data = {
          dialogue: {
            questionContent: this.messageList2[this.messageList2.length - 2].content,
            answers: this.messageList2[this.messageList2.length - 1].content,
            dialogueId: this.messageList2[this.messageList2.length - 1].id,
            created
          }
        }
        // console.log(data)
        commitQuestion(data).then(res => {
          this.getUserInfo()
        })
      },
      // 获取用户信息
      getUserInfo() {
        if(this.isLogin) {
          getCommitQuestionInfo().then(res => {
            this.isChangeUserInfo = false
            console.log(res)
            const data = {
              '今日免费额度剩余次数': +res.data['今日免费额度剩余次数'],
              '剩余总提问次数': +res.data['剩余总提问次数'],
              '剩余购买提问次数': +res.data['剩余购买提问次数'],
              '用户会员等级': +res.data['用户会员等级']
            }
            this.userInfo = data
          })
        }
      },
      // 获取用户手机号
      getPhone() {
        if(this.isLogin) {
          getPhone().then(res => {
            console.log(res)
            this.phone = res.data
          })
        }
      }
    },
    beforeDestroy(){
      if (this.socket != null) {
        this.socket.close();
        this.socket = null;
        console.log('已关闭连接')
        this.isConnected = false
      }
    },
    created(){
      this.watchWidth();
      let that = this
      this.openSocket()
    },
    mounted(){
      let that = this
      this.loadLocalChatList()
      setInterval(()=>{
        that.coopText()
      },1000)
      this.watchWidth();
      // this.openSocket()
      this.$nextTick(() => {
        this.$refs.scrollContainer.scrollIntoView(false);
      });
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.windowHeight = window.fullHeight;  // 高
      this.windowWidth = window.fullWidth; // 宽
      if (this.windowWidth<800){
        this.phoneWidth = 100
        this.phoneSWidth = 90
        this.phoneBuWidth = 9
        this.logowidth = 55
        this.menuWidth = 100
        this.leftMenu = false
        this.openmenuWidth = 100
        this.phonePaddingTop = 50
        this.loginBoxWidth = 99
        this.isPhone = true
      }else{
        this.phoneWidth = 51
        this.phoneSWidth = 45
        this.phoneBuWidth = 22
        this.logowidth = 20
        this.menuWidth = 18
        this.leftMenu = true
        this.openmenuWidth = 100
        this.phonePaddingTop = 20
        this.loginBoxWidth = 50
        this.isPhone = false
      }
      // 如果token存在则说明已经登录
      if(getToken() !== '' && getToken() !== undefined) {
        this.isLogin = true
        this.getUserInfo()
        this.getPhone()
      }
    },
    watch: {
      windowHeight (val) {
        let that = this;
        console.log("实时屏幕高度：",val, that.windowHeight );

      },
      windowWidth (val) {
        let that = this;
        console.log("实时屏幕宽度：",val, that.windowHeight );
        if (val<800){
          this.phoneWidth = 100
          this.phoneSWidth = 90
          this.phoneBuWidth = 9
          this.logowidth = 55
          this.menuWidth = 100
          this.leftMenu = false
          this.openmenuWidth = 100
          this.phonePaddingTop = 50
          this.loginBoxWidth = 99

        }else{
          this.phoneWidth = 51
          this.phoneSWidth = 45
          this.phoneBuWidth = 22
          this.logowidth = 20
          this.menuWidth = 18
          this.leftMenu = true
          this.openmenuWidth = 82
          this.phonePaddingTop = 20
          this.loginBoxWidth = 50

        }
      },
      chatList(val){
        this.wrightLocalChatList()
        console.log("写入缓存")
      }
    },
    computed: {
      phoneX() {
        let phone = this.phone
        let res = ''
        for(let i = 0; i < phone.length; i++) {
          if(i > 2 && i < phone.length - 2) {
            res += '*'
          }else {
            res += phone[i]
          }
        }

        return res
      }
    }
  };
</script>

<style scoped>
  .pc-chat-container{
    display: flex;
    width: 100%;
    height: 95vh;
    margin-top: 5vh;
  }
  /*电脑侧边栏*/
  .pc-sidebar{
    display: flex;
    flex-direction: column;
    /*width: 18%;*/
    height: 100%;
    background-color: #202123;
    color: white;
  }
  /*电脑对话窗*/
  /*滚动条样式*/
  .chatgpt-box::-webkit-scrollbar {
    width: 9px;
  }
  .chatgpt-box::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    background: #565869;
  }
  .chatgpt-box::-webkit-scrollbar-track {
    /*box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);*/
    border-radius: 0;
    background: transparent;
  }
  .pc-dialog-box{
    display: flex;
    flex-direction: column;
    /*width: 82%;*/
    height: 77vh; /* 容器高度 */
    overflow-y: hidden; /* 垂直滚动条 */
    background-color: #FFFFFF;
  }
  /*对话框*/
  .chatgpt-box{
    width: 100%;
    height: auto;
    background: transparent;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    max-height: 80vh;
    overflow-y: scroll;
    position: relative;
    padding-top: 20px;
    padding-bottom: 3vh;
    align-content: flex-start;
    padding-right: 0;
  }
  .chatgpt-box::-webkit-scrollbar{width:0;}
  .some-an{
    width: 100%;
    overflow-x: hidden;

  }
  .some-anin{
    width:100%;
  }
  .content-chat{
    font-size: 17px;
    background: transparent;
    padding: 0.75rem 15px;
    display: flex;
    width: 100%;
    justify-content: center;
  }
  .content-chat-2{
    font-size: 17px;
    /*background: #e2e2e2;*/
    padding: 0.75rem 15px;
    display: flex;
    height: auto;
    /*width: 95%;*/
    background: rgb(247,247,248);
    justify-content: center;
    position: relative;
    flex-wrap: wrap;
    flex-direction: row;
  }
  .content-chat-2 .copy-contents{
    opacity: 0;
  }
  .content-chat-2:hover .copy-contents {
    opacity: 1;
    box-shadow: 0px 1px 3px;
    cursor: pointer;
  }
  i {
    cursor: pointer;
  }
  .content-chat-2 img{
    width: 30px;
    height: 30px;
    border-radius: 5px;
    position: relative;
    margin-right: 10px;
  }
  .content-chat img{
    width: 30px;
    height: 30px;
    border-radius: 5px;
    position: relative;
    margin-right: 10px;
  }
  .content-chat-2 span,.content-chat span{
    /*display: flex;*/
    align-items: center;
    text-align: justify;
    white-space: pre-wrap;
    padding: 3px;
  }
  .content-icon{
    height: 100%;
    display: flex;
    align-items: flex-start;
    width: auto;
  }
  /*对话窗中聊天部分*/
  .pc-dialog-box-chat{
    display: flex;
    width: 100%;
    height: 100%;
    background-color: #FFFFFF;
  }
  /*电脑输入框容器*/
  .pc-import-box{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-items: center;
    width: 82%;
    height: 20%;
    background-color: white;
    position: fixed;
    bottom: 0;
  }
  /*电脑输入框*/
  .pc-import{
    display: flex;
    align-items: center;
    background-color: white;
    margin-top: 45px;
    width: 70%;
    height: 53px;
    box-shadow: 0px 0px 6px 2px rgba(167, 165, 165, 0.2);
    border-radius: 0.375rem;
    border-color: rgba(0,0,0,.1);
    border-width: 1px;
  }
  /*产品提示*/
  .product-tips{
    font-size: .75rem;
    line-height: 1rem;
    text-align: center;
    color: rgba(0,0,0,.5);
    margin-top: 10px;
  }
  /*输入框样式*/
  .inputStyle{
    border: none;
    outline: none;
    font-size: 19px;
    padding-left: 1rem;
    width: 92%;
  }
  /*放发送图标的容器*/
  .pc-import-button-box{
    width: 28px;
    height: 23px;
    align-items: center;
    justify-content: center;
    /*background-color: #ECECF1;*/
    border-radius: 5px;
  }
  .pc-import-button-box:hover{
    background: #ECECF1;
  }
  /*发送图标*/
  .post-button{
    /*width: 40px;*/
    align-items: center;
    margin-top: 1px;
    color: #DDDDE3;
    font-size: 21px;
    /*font-weight: 600;*/
    margin-left: 2px;
  }
  .pc-new-box{
    display: flex;
    width: 80%;
    margin-left: 3%;
    margin-top: 10px;
    height: 50px;
    align-items: center;
    border-width: 1px;
    border-radius: 0.375rem;
    box-shadow: 0px 0px 0px 1px hsla(0,0%,100%,.2);
    font-size: .875rem;
    line-height: 1.25rem;
    cursor:pointer;
  }
  .pc-new-box:hover{
    background: #2c3e50;
  }
  /*用户账号*/
  .pc-user{
    display: flex;
    flex-direction: column;
    /*align-items: center;*/
    /*justify-items: center;*/
    width: 18%;
    height: 15%;
    background-color: #202123;
    position: fixed;
    bottom: 0;
    border-top: 1px solid hsla(0,0%,100%,.2);
  }
  /*对话列表容器*/
  .pc-post-list-box{
    display: flex;
    flex-direction: column;
    /*width: 18%;*/
    height: 76vh; /* 容器高度 */
    overflow-y: auto; /* 垂直滚动条 */
    background-color: #202123;
    margin-top: 8px;
  }
  /*对话列表*/
  .pc-post-list{
    display: flex;
    /*height: 8200px;*/
    background-color: #202123;
    justify-content: center;
  }
  .pc-post{
    display: flex;
    width: 94%;
    /*height: 22px;*/
    border-radius: 0.375rem;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    padding-top: 0.75rem;
    padding-bottom: 0.75rem;
    align-items: center;
    margin-bottom: 0.75rem;
  }
  .pc-post:hover{
    background-color: #434550;
    cursor: pointer;
  }
  .pc-post:active{
    background-color: #3e3f4a;

  }
  .pc-post-active{
    background-color: #434550;
  }
  /*滚动条样式*/
  div::-webkit-scrollbar {
    width: 9px;
  }
  div::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
    background: #565869;
  }
  div::-webkit-scrollbar-track {
    /*box-shadow: inset 0 0 5px rgba(255, 255, 255, 0.2);*/
    border-radius: 0;
    background: #202123;
  }
  .post-icon{
    padding-left: 0.92rem;
  }
  .post-text{
    padding-left: 0.92rem;
    width: 70%;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
    font-size: 17px;
  }
  /*升级服务*/
  .update-service{
    display: flex;
    width: 94%;
    height: 46px;
    border-radius: 0.375rem;
    margin-left: 3%;
    align-items: center;
    margin-top: 10px;
  }
  .update-service:hover{
    background-color: #434550;
  }
  .new-box{
    color:#202123;
    font-weight: 600;
    width: 40px;
    height: 20px;
    font-size: .80rem;
    border-radius: 0.375rem;
    background-color: #FAE69E;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: auto;
    margin-right: 12px;
  }
  /*用户账号*/
  .user-account{
    display: flex;
    width: 94%;
    height: 46px;
    border-radius: 0.375rem;
    margin-left: 3%;
    align-items: center;
    cursor: pointer
  }
  .user-account:hover{
    background-color: #434550;
  }
  .mc-box{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 11px;
    font-size: 5px;
    font-weight: 500;
    width: 23px;
    height: 23px;
    background-color: #9A59B5;
    border-radius: 0.175rem;
  }
  .reload-button{
    border: 1px solid #a9a9a9;
    /*width: 100px;*/
    display: flex;
    justify-content: center;
    padding: 10px 35px;
    border-radius: 5px;
    left: 50%;
    transform: translateX(-85px);
    cursor: pointer;
    position: absolute;
    top: -15px;
    color: #9e9e9e;
  }
  .reload-button:hover{
    background-color: ghostwhite;
  }
  .el-icon-menu{
    font-size: 42px;
    color:white
  }
  .left-top-menu-button{
    position: absolute;
    left: 0;
    top: 0;
    border: 1px solid black;
    border-bottom-right-radius: 35px;
    padding: 5px 10px 10px 5px;
    background: black;
    cursor: pointer;
  }
  .phone-sidebar{
    z-index: 10000;
  }
  .el-dialog{
    width: auto
  }
  .el-dialog-computer{
    width: 50%;
  }
  .login-box{
    left: 0;
    background: white;
    padding: 20px;
    position: relative;
    bottom: 50px;
    z-index: 2005;
  }
  .dialog-box{
    position: fixed;
    background: #808080a6;
    width: 100%;
    height: 100%;
    z-index: 2005;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .login-tip{
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }
  .buy-vip {
    cursor: pointer;
  }
  .logo-hasno {
    position: absolute;
    top: 50%;
    left: 50%;
    /* transform: translateX(-50%); */
    /* transform: translateY(-50%); */
    transform: translate(-50%, -50%);
    height: 100px;
    width: 100px;
  }
  .logo-hasno img {
    height: 100px;
    width: 100px;
  }
  .logo-warp {
    position: relative;
    height: 100%;
  }
  .aiChallenge {
    position: fixed;
    right: 3%;
    top:3%;
    z-index: 1;
  }
  .wx-login {
    display: block;
    /* padding: 10px; */
    margin: 0 auto;
    width: 45px;
    height: 45px;
    border-radius: 25px;
    border: solid 1px #E6E6E9;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
  }
  .wx-login-wrap {
    text-align: center;
    margin-top: 10px;
    display: flex;
    justify-content: space-around;
  }
  .wx-login-bottom {
    display: block;
    width: 60%;
    text-align: center;
    background: linear-gradient(to right, #7FE9AB, #29CCE5);
    font-size: 18px;
    padding: 10px 0;
    border-radius: 20px;
    color: white;
    font-weight: 500;
  }
  .group-image {
    width: 300px;
  }
  @media screen and (max-width: 750px) {
    .group-image {
      width: 80%;
    }
  }
  .top-box{
    width: 100vw;
    height: 60px;
    position: fixed;
    top: 0px;
    /*background: #0a7c86;*/
    background: linear-gradient(90deg, #d4e3fe, #f8ebe4);
    display: flex;
    color:#000;
    align-items: center;
    z-index: 100;
  }

  .top-left-title{
    margin-left: 35px;
    width: 250px;
    font-size: 28px;
    color: #000;
    cursor: pointer;
    font-weight: bold;
  }

  .top-menu-list{
    display: flex;
  
  }
  .top-menu-list div{
  
    width: 100px;
    color: #000;
    font-weight: bold;
    text-align: center;
    padding-bottom: 5px;
  }

  .active-no{
    position: relative;
    top: 5px;
    cursor:pointer;
  }

  .user-box{
    display: flex;
    position: absolute;
    right: 50px;
    top: 13px;
  }
  .user-box div{
    margin-left: 20px;
  }

  .center-box {

    max-width: 1320px;
    height: auto;
    margin: 0 auto;
    margin-top: 80px;
  }

  .menu-list {
    display: flex;
    flex-wrap: wrap;
    border: 1px solid #b4b4b4;
    border-radius: 5px;
  }

  .menu-box {
    width: 100%;
    /*background: eef7ff;*/
    display: flex;
  }

  .menu-title {
    padding: 10px;
    width: 15%;
    background: #eef7ff;
    font-weight: bold;
    text-align: center;
  }
</style>
